package fun.wlfj.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import fun.wlfj.dao.IPayBackDAO;
import fun.wlfj.dbc.IConnectionManager;
import fun.wlfj.dbc.MySQLConnection;
import fun.wlfj.vo.PayBack;

public class PayBackDaoImpl extends AbsDaoImpl implements IPayBackDAO {

	public PayBackDaoImpl(Connection conn) {
		super(conn);
	}
 
	@Override
	public int createPayBack(int PayListID) {
		// 我们应该能够返回当前新创建的id 不然没办法添加商品
		int id = -1;
		try {
			PreparedStatement pstsm = conn.prepareStatement("insert into PayBack(PayListID) values(?);");
			pstsm.setInt(1, PayListID);
			if(pstsm.executeUpdate() == 1) {
				PreparedStatement pstsm1 = conn.prepareStatement("select max(PayBackID) from PayBack where PayListID = ?;");
				pstsm1.setInt(1, PayListID);
				ResultSet rs = pstsm1.executeQuery();
				rs.next();
				id = rs.getInt(1);
			}else {
				id = -1;
			}
			IConnectionManager.closePstsm(pstsm);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return id;
	}

	@Override
	public String setPayed(PayBack pb) {
		pb.setIsValid(true);
		return "ok";
	}

	@Override
	public String setCancled(PayBack pb) {
		String msg = null;
		try {
			PreparedStatement pstsm = conn.prepareStatement("update PayBack set IsValid = 0 where PayBackID = ?;");
			pstsm.setInt(1, pb.getPayBackID());
			pb.setIsValid(false);
			if(pstsm.executeUpdate() == 1) {
				msg = "ok";
			}else {
				msg = "error";
			}
			IConnectionManager.closePstsm(pstsm);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return msg;
	}

	@Override
	public PayBack getPayBackByID(int PayListID) {
		PayBack pb = null;
		try {
			PreparedStatement pstsm = conn.prepareStatement("select * from PayBack where PayListID = ?;");
			pstsm.setInt(1, PayListID);
			ResultSet rs = pstsm.executeQuery();
			if(rs.next()) {
				pb = new PayBack(rs.getInt(1), rs.getInt(2), rs.getDate(3), rs.getInt(4) == 1);
			}
			IConnectionManager.closePstsm(pstsm);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return pb;
	}
	
	public static void main(String[] args) {
		IConnectionManager manager = new MySQLConnection();
		PayBackDaoImpl test = new PayBackDaoImpl(manager.getConn());
		PayBack pb1 = test.getPayBackByID(13);
		System.out.println( "获取已有pb：" + pb1);
		int id = test.createPayBack(5);
		PayBack pb2 = test.getPayBackByID(id);
		System.out.println("新创建pb：" + pb2);
	}

}
